package com.example.shop.common.config;


import com.example.shop.common.enums.SessionAttributeKey;
import com.example.shop.common.enums.WebSocketUserPropertiesKey;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Map;

public class InformWebSocketConfigurator extends ServerEndpointConfig.Configurator{
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        //获取用户自定义的参数数据
        Map<String, Object> userProperties = sec.getUserProperties();
        //如果存在与此请求关联的HTTP Session对象，则返回该对象，否则返回null
        HttpSession session = (HttpSession) request.getHttpSession();
        if(session!=null){
            //保存建立的连接时，该httpSession的id
            userProperties.put(WebSocketUserPropertiesKey.HTTP_SESSION_ID.getKey(), session.getId());
            //获取该httpSession里保存的客户端ip，注意：这个httpSession是指websocket的
            String clientIp = (String) session.getAttribute(SessionAttributeKey.CLIENT_IP.getKey());
            //将客户端ip地址保存到websocket的session的用户参数数据里
            userProperties.put(WebSocketUserPropertiesKey.CLIENT_IP.getKey(), clientIp);
        }
    }
}
